package com.cn.jinl.service;


import com.cn.jinl.api.*;
import com.cn.jinl.dao.BoxManageMapper;
import com.cn.jinl.dao.ProductStorageMapper;
import com.cn.jinl.dao.ProductStorageOutRelateMapper;
import com.cn.jinl.dao.ProductStorageRelateMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.GenerateUUID;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@EnableScheduling
@Service
public class ProductStorageRelateServiceImpl implements IProductStorageRelateService {

    @Autowired
    private ProductStorageRelateMapper productStorageRelateMapper;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private IProductStorageService productStorageService;

    @Autowired
    private ProductStorageMapper productStorageMapper;

    @Autowired
    private IOnDutyPersonService onDutyPersonService;

    @Autowired
    private IPlanManageService planManageService;

    @Autowired
    private IOnDutyProductService onDutyProductService;

    @Autowired
    private ProductStorageOutRelateMapper productStorageOutRelateMapper;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private BoxManageMapper boxManageMapper;

    @Override
    public List<ProductStorageRelate> getProductStorageRelateList(ProductStorageRelate productStorageRelate) throws Exception {
        return null;
    }

    @Override
    public List<ProductStorageRelate> getProductStorageRelateToday() throws Exception {
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        ProductStorageRelateExample example = new ProductStorageRelateExample();
        example.createCriteria().andDutyDayEqualTo(dutyDay).andWhiteDayEqualTo(whiteDay);
        List<ProductStorageRelate> relates = productStorageRelateMapper.selectByExample(example);
        return relates;
    }

    @Override
    public List<ProductStorageRelate> getOnDutyStorageHisByPlanId(String planId) throws Exception {
        return productStorageRelateMapper.selectOnDutyStorageHisByPlanId(planId);
    }



    @Override
    public List<ProductStorageRelate> getProductStorageRelateListByTaskId(String taskId,String planId) throws Exception {
        if(StringUtils.isEmpty(taskId)||StringUtils.isEmpty(planId)){
            return Lists.newArrayList();
        }
        ProductStorageRelateExample example = new ProductStorageRelateExample();
        example.createCriteria().andTaskIdEqualTo(taskId).andPlanIdEqualTo(planId);
        return productStorageRelateMapper.selectByExample(example);
    }

    @Override
    public String addBatchProductStorageRelates(List<ProductStorageRelate> productStorageRelates) throws Exception{
        if(CollectionUtils.isEmpty(productStorageRelates)){
            return "参数异常！";
        }
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String nowWhiteDay = dutyMap.get("whiteDay");

        String taskId = productStorageRelates.get(0).getTaskId();
        OnDutyProduct existTask = onDutyProductService.getPlanIdByTaskId(taskId);
        if(null == existTask){
            return "计划任务不存在！";
        }
        if(!StringUtils.equals("2",existTask.getProductStatus())){
            return "计划任务未开始！";
        }
        if(!StringUtils.equals(dutyDay,existTask.getDutyDay())||!StringUtils.equals(nowWhiteDay,existTask.getWhiteDay())){
            return "计划任务不在该班次内！";
        }
        String planId = existTask.getPlanId();
        PlanManage existPlan = planManageService.getPlanManageById(planId);
        if(null == existPlan){
            return "计划不存在！";
        }
        if(!StringUtils.equals(existPlan.getPlanStatus(),"2")){
            return "计划未下发或者已完成！";
        }
        List<BoxManage> boxManages = Lists.newArrayList();
        List<String> boxes = Lists.newArrayList();
        for(ProductStorageRelate productStorageRelate :productStorageRelates){
            if(StringUtils.isEmpty(productStorageRelate.getBoxCode())){
                return "箱码不能为空";
            }else if(StringUtils.isEmpty(productStorageRelate.getTaskId())){
                return "任务ID不能为空";
            }else if(boxes.contains(productStorageRelate.getBoxCode())){
                return "箱码不能重复";
            }
            productStorageRelate.setPlanId(planId);
            boxes.add(productStorageRelate.getBoxCode());
            productStorageRelate.setGradeValue(existPlan.getGradeValue());
            productStorageRelate.setItemTypeId(existPlan.getItemTypeId());
            BoxManage boxManage = new BoxManage();
            boxManage.setBoxCode(productStorageRelate.getBoxCode());
            boxManage.setPrintCode("1");
            boxManage.setCodeStatus("1");
            boxManages.add(boxManage);
        }
        BoxManageExample boxManageExample = new BoxManageExample();
        boxManageExample.createCriteria().andBoxCodeIn(boxes).andCodeStatusEqualTo("1");

        List<BoxManage> existCodes = boxManageMapper.selectByExample(boxManageExample);
        if(!CollectionUtils.isEmpty(existCodes)){
            String error = "【";
            for(BoxManage b : existCodes){
                error += b.getBoxCode()+",";
            }
            error+="】已经入库，请不要重复入库！";
            return error;
        }

        String locked = onDutyPersonService.getOnDutyLockedByDutyAndWhite(dutyDay,nowWhiteDay);
        if(Integer.parseInt(locked) > 5){
            return "产量已经被锁定5次，无法报工！";
        }

//        String planStatus = "";
//        String completeNum = StringUtils.isEmpty(existPlan.getCompleteNum())?"0":existPlan.getCompleteNum();
//        if((Integer.parseInt(completeNum)+productStorageRelates.size())>= Double.parseDouble(existPlan.getPeieceNum()) ){
//            planStatus = "3";
//            String resp = orderService.updateOrderProduceComplete(planId);
//            if(StringUtils.isNotEmpty(resp)){
//                return resp;
//            }
//        }
        String resp = planManageService.updatePlanManageTaskCount(planId,productStorageRelates.size(),"");
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        int count = productStorageRelateMapper.batchInsertProdStorageRelate(productStorageRelates);
        if(count < 1){
            throw new Exception("插入表异常");
        }
        if(!CollectionUtils.isEmpty(boxManages)){
            count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
            if(count < 1){
                throw new Exception("更新箱码失败！");
            }
        }
        return CommonUtil.outStr(count);
    }


    //平库-----------扫码入库 备货任务id为111写死
    @Override
    public String addBatchProductStorageRelates1(List<ProductStorageRelate> productStorageRelates) throws Exception{
        String planId = "111";
        List<BoxManage> boxManages = Lists.newArrayList();
        List<String> boxes = Lists.newArrayList();
        String  storageId = CommonUtil.generateRandomNum("storage_");
        for(ProductStorageRelate productStorageRelate :productStorageRelates){
            if(StringUtils.isEmpty(productStorageRelate.getBoxCode())){
                return "箱码不能为空";
            }else if(boxes.contains(productStorageRelate.getBoxCode())){
                return "箱码不能重复";
            }
            productStorageRelate.setPlanId(planId);
            productStorageRelate.setStorageId(storageId);
            boxes.add(productStorageRelate.getBoxCode());
            productStorageRelate.setGradeValue(productStorageRelate.getGradeValue());
            productStorageRelate.setItemTypeId(productStorageRelate.getItemTypeId());
            productStorageRelate.setUserName(productStorageRelate.getUserName());
            BoxManageExample boxManageExample = new BoxManageExample();
            boxManageExample.createCriteria().andBoxCodeEqualTo(productStorageRelate.getBoxCode());
            List<BoxManage> boxManages1 = boxManageMapper.selectByExample(boxManageExample);
            if (boxManages1.size()>0){
                BoxManage boxManage = new BoxManage();
                boxManage.setBoxCode(productStorageRelate.getBoxCode());
                boxManage.setPrintCode("1");
                boxManage.setCodeStatus("2");
                boxManages.add(boxManage);
            }else {
                String error="请检查箱码是否正确";
                return error;
            }

        }
        BoxManageExample boxManageExample = new BoxManageExample();
        boxManageExample.createCriteria().andBoxCodeIn(boxes).andCodeStatusEqualTo("1");

        List<BoxManage> existCodes = boxManageMapper.selectByExample(boxManageExample);
        if(!CollectionUtils.isEmpty(existCodes)){
            String error = "【";
            for(BoxManage b : existCodes){
                error += b.getBoxCode()+",";
            }
            error+="】已经入库，请不要重复入库！";
            return error;
        }
        int count = productStorageRelateMapper.batchInsertProdStorageRelate1(productStorageRelates);
        if(count < 1){
            throw new Exception("插入表异常");
        }
        ProductStorage productStorage = new ProductStorage();
        String yearMoth = generateUUID.getYearMoth();
        String key = yearMoth+"storage";
        int num = generateUUID.getNumberFlag(key);
        String code = "RK"+yearMoth+generateUUID.getThreeNumStr(num);
        productStorage.setId(storageId);
        productStorage.setStorageType("2");
        productStorage.setStorageStatus("1");
        productStorage.setStorageCode(code);
        productStorage.setStorageUserName("admin");
        productStorage.setStorageCount(boxes.size());
        productStorage.setStorageGradeCount(1);
        productStorage.setStorageUserId("");
        int counts = productStorageMapper.insertSelective(productStorage);
        if(counts < 1){
            throw new Exception("插入表异常");
        }
        if(!CollectionUtils.isEmpty(boxManages)){
            count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
            if(count < 1){
                throw new Exception("更新箱码失败！");
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public List<ProductStorageRelate> getOrderGradesByAppMh(QueryForm queryForm) throws Exception {
        List<ProductStorageRelate> productStorageRelates = productStorageRelateMapper.getOrderGradesByAppMh(queryForm);
        return productStorageRelates;
    }

    @Override
    public String updateLockOnDutyProduct(ProductStorageRelate productStorageRelates) throws Exception {
        String dutyDay = productStorageRelates.getDutyDay();
        String whiteDay = productStorageRelates.getWhiteDay();
        if(StringUtils.isEmpty(dutyDay)||StringUtils.isEmpty(whiteDay)){
            return "参数异常！";
        }

        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String nowDuty = dutyMap.get("dutyDay");
        if(!StringUtils.equals(nowDuty,dutyDay)){
            return "参数异常【dutyDay】！";
        }
        String nowWhiteDay = dutyMap.get("whiteDay");
        if(!StringUtils.equals(nowWhiteDay,whiteDay)){
            return "参数异常【whiteDay】！";
        }
        ProductStorageRelateExample example = new ProductStorageRelateExample();
        example.createCriteria().andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andStorageIdIsNull();

        List<ProductStorageRelate> exists = productStorageRelateMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(exists)){
            return "未查询有新入库数据！";
        }

        Set<String> taskTypeSet = Sets.newHashSet();
        for(ProductStorageRelate relate : exists ){
            taskTypeSet.add(relate.getTaskId());
        }
        QueryForm queryForm = new QueryForm();
        queryForm.setWhiteDay(whiteDay);
        queryForm.setDutyDay(dutyDay);
        String storageId = "";
        storageId = productStorageRelateMapper.selectStorageIdByWhiteDay(queryForm);
        if(StringUtils.isNotEmpty(storageId)){
            ProductStorage existStorage = productStorageService.getOnlyProductStorageById(storageId);
            if(null == existStorage){
                return "查询之前入库数据异常！";
            }
            existStorage.setStorageCount(existStorage.getStorageCount()+exists.size());
            existStorage.setStorageGradeCount(existStorage.getStorageGradeCount()+taskTypeSet.size());
            String resp = productStorageService.updateProductStorage(existStorage);
            if(StringUtils.isNotEmpty(resp)){
                return resp;
            }
        }else{
            storageId = CommonUtil.generateRandomNum("storage_");
            String yearMoth = generateUUID.getYearMoth();
            String key = yearMoth+"storage";
            int num = generateUUID.getNumberFlag(key);
            String code = "RK"+yearMoth+generateUUID.getThreeNumStr(num);
            ProductStorage productStorage = new ProductStorage();
            productStorage.setId(storageId);
            productStorage.setStorageCode(code);
            productStorage.setStorageType("1");
            productStorage.setStorageStatus("1");
            productStorage.setStorageCount(exists.size());
            productStorage.setStorageGradeCount(taskTypeSet.size());
            productStorage.setStorageUserName(productStorageRelates.getUserName());
            productStorage.setStorageUserId(productStorageRelates.getUserId());
            String resp = productStorageService.addProductStorage(productStorage);
            if(StringUtils.isNotEmpty(resp)){
                return resp;
            }
        }

        String resp = onDutyPersonService.updateOnDutyPersonLocked(dutyDay,whiteDay);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        ProductStorageRelate update = new ProductStorageRelate();
        update.setStorageId(storageId);
        ProductStorageRelateExample example1 = new ProductStorageRelateExample();
        example1.createCriteria().andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay);
        int count = productStorageRelateMapper.updateByExampleSelective(update,example1);
        if(count < 1){
            throw new Exception("更新表异常！");
        }
        return "";
    }

    @Override
    public String deleteOnDutyProductCodeBox(ProductStorageRelate productStorageRelate) throws Exception {
        String taskId = productStorageRelate.getTaskId();
        String planId = productStorageRelate.getPlanId();
        String code = productStorageRelate.getBoxCode();
        if(StringUtils.isEmpty(taskId)||StringUtils.isEmpty(planId)||StringUtils.isEmpty(code)){
            return "参数错误";
        }
        ProductStorageRelateExample example = new ProductStorageRelateExample();
        example.createCriteria().andTaskIdEqualTo(taskId).andPlanIdEqualTo(planId).andBoxCodeEqualTo(code);
        int count = productStorageRelateMapper.deleteByExample(example);
        if(count != 1){
            return "删除异常！";
        }
        BoxManageExample boxManageExample = new BoxManageExample();
        boxManageExample.createCriteria().andBoxCodeEqualTo(code);
        BoxManage updateBox = new BoxManage();
        updateBox.setCodeStatus("0");
        count = boxManageMapper.updateByExampleSelective(updateBox,boxManageExample);
        if(count != 1){
            throw new Exception("回退箱码状态异常");
        }
        String resp = planManageService.updatePlanManageTaskCount(planId,-1,"");
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return "";
    }

    @Override
    public Map<String, Integer> getLeftProductStorage() throws Exception {
        Map<String,Integer> leftMap = Maps.newHashMap();
        List<ProductStorageRelate> storageRelates = productStorageRelateMapper.selectLeftProductStorages();
        if(CollectionUtils.isEmpty(storageRelates)){
            return leftMap;
        }
        for(ProductStorageRelate relate:storageRelates){
            String key = relate.getItemTypeId()+"-"+relate.getGradeValue();
            leftMap.put(key,relate.getStorageInCount());
        }

        List<ProductStorageOutRelate> outRelates = productStorageOutRelateMapper.selectOutLeftProductStorages();
        for(ProductStorageOutRelate outRelate:outRelates){
            String key = outRelate.getItemTypeId()+"-"+outRelate.getGradeValue();
            if(leftMap.containsKey(key)){
                int leftCount = leftMap.get(key) - outRelate.getOutTotalCount();
                leftMap.put(key,leftCount);
            }
        }
        return leftMap;
    }

    @Override
    public Integer getCount(ProductStorageRelateExample example) {
        return productStorageRelateMapper.getCount(example);
    }

    @Override
    public int getCountByReporting(QueryForm queryForm) {
        return productStorageRelateMapper.getCountByReporting(queryForm);
    }

    @Override
    public Map<String, Integer> getCountByReportingBatch(String itemId, List<String> gradeValues) {
        if (CollectionUtils.isEmpty(gradeValues)) {
            return new HashMap<>();
        }

        List<ProductStorageRelate> results = productStorageRelateMapper.selectReportingCountBatch(itemId, gradeValues);

        // key为gradeValue，value为数量
        return results.stream()
                .collect(Collectors.toMap(
                        ProductStorageRelate::getGradeValue,
                        ProductStorageRelate::getCount
                ));
    }

    @Override
    public String updateStorageInAndOutBoxCodeStep1() throws Exception {
        List<ProductStorageRelate> relates = productStorageRelateMapper.selectProductStorageRelateGroupByCode();
        List<String> repeatCodes = Lists.newArrayList();
        for(ProductStorageRelate relate:relates){
            if(relate.getCount() == 2){
                repeatCodes.add(relate.getBoxCode());
            }
        }
        List<String> boxs = boxManageMapper.selectBoxManageWithNotUse();
        ProductStorageRelateExample example = new ProductStorageRelateExample();
        List<ProductStorageRelate> storageRelates = productStorageRelateMapper.selectByExample(example);
        Map<String,ProductStorageRelate> maps = new HashMap<>();
        Map<String,ProductStorageRelate> updateMaps = Maps.newHashMap();
        for(ProductStorageRelate relate:storageRelates){
            String boxCode = relate.getBoxCode();
            if(repeatCodes.contains(boxCode)){
                if(!maps.containsKey(boxCode)){
                    maps.put(boxCode,relate);
                }else{
                    if(!StringUtils.equals(relate.getItemTypeId(), maps.get(boxCode).getItemTypeId())||!StringUtils.equals(relate.getGradeValue(), maps.get(boxCode).getGradeValue())){
                        String newCode = boxs.get(0);
                        boxs.remove(0);
                        relate.setOldCode(relate.getBoxCode());
                        relate.setBoxCode(newCode);
                        updateMaps.put(boxCode,relate);
                    }
                }
            }
        }

        List<ProductStorageRelate> storageUpdate = Lists.newLinkedList();
        List<String> storageUpdateCode = Lists.newLinkedList();
        for(String key:updateMaps.keySet()){
            storageUpdate.add(updateMaps.get(key));
            storageUpdateCode.add(key);
        }

        List<ProductStorageOutRelate> updateOutRelates = Lists.newArrayList();
        ProductStorageOutRelateExample example1 = new ProductStorageOutRelateExample();
        example1.createCriteria().andBoxCodeIn(storageUpdateCode);
        List<ProductStorageOutRelate> outRelates = productStorageOutRelateMapper.selectByExample(example1);
        for(ProductStorageOutRelate relate:outRelates){
            ProductStorageRelate storageRelate = updateMaps.get(relate.getBoxCode());
            if(StringUtils.equals(storageRelate.getItemTypeId(),relate.getItemTypeId()) && StringUtils.equals(storageRelate.getGradeValue(),relate.getGradeValue())){
                relate.setOldCode(relate.getBoxCode());
                relate.setBoxCode(storageRelate.getBoxCode());
                updateOutRelates.add(relate);
            }
        }
        for(ProductStorageRelate relate:storageUpdate){
            ProductStorageRelateExample example2 = new ProductStorageRelateExample();
            example2.createCriteria().andBoxCodeEqualTo(relate.getOldCode()).andItemTypeIdEqualTo(relate.getItemTypeId()).andGradeValueEqualTo(relate.getGradeValue());
            ProductStorageRelate update = new ProductStorageRelate();
            update.setBoxCode(relate.getBoxCode());
            productStorageRelateMapper.updateByExampleSelective(update,example2);
        }

        for(ProductStorageOutRelate relate:updateOutRelates){
            ProductStorageOutRelateExample example3 = new ProductStorageOutRelateExample();
            example3.createCriteria().andBoxCodeEqualTo(relate.getOldCode()).andItemTypeIdEqualTo(relate.getItemTypeId()).andGradeValueEqualTo(relate.getGradeValue());
            ProductStorageOutRelate update = new ProductStorageOutRelate();
            update.setBoxCode(relate.getBoxCode());
            productStorageOutRelateMapper.updateByExampleSelective(update,example3);
        }


        return null;
    }

    @Override
    public String updateStorageInAndOutBoxCodeStep2() throws Exception {
        ProductStorageRelateExample example = new ProductStorageRelateExample();
        example.createCriteria().andBoxCodeIsNotNull();
        List<ProductStorageRelate> relates = productStorageRelateMapper.selectByExample(example);

        Map<String,ProductStorageRelate> relateMap = Maps.newHashMap();
        for(ProductStorageRelate relate:relates){
            relateMap.put(relate.getBoxCode(),relate);
        }

        ProductStorageOutRelateExample example1 = new ProductStorageOutRelateExample();
        example1.createCriteria().andBoxCodeIsNotNull();
        List<ProductStorageOutRelate> outRelates = productStorageOutRelateMapper.selectByExample(example1);
        List<ProductStorageOutRelate> updates = Lists.newArrayList();
        for(ProductStorageOutRelate outRelate:outRelates){
            String boxCode = outRelate.getBoxCode();
            if(relateMap.containsKey(boxCode)){
                ProductStorageRelate relate =  relateMap.get(boxCode);
                if(!StringUtils.equals(relate.getItemTypeId(),outRelate.getItemTypeId())|| !StringUtils.equals(relate.getGradeValue(),outRelate.getGradeValue())){
                    ProductStorageOutRelate update  = new ProductStorageOutRelate();
                    update.setBoxCode(boxCode);
                    update.setGradeValue(relate.getGradeValue());
                    update.setItemTypeId(relate.getItemTypeId());
                    updates.add(update);
                }
            }
        }
        int maxSize = 100;
        int batch = (updates.size()/maxSize)+1;
        for(int i=0;i <= batch ;i ++){
            int start = i*maxSize;
            if(start >= updates.size()){
                break;
            }
            int end = (i+1)*maxSize;
            if(end >= updates.size()){
                end = updates.size();
            }
            List<ProductStorageOutRelate> subList = updates.subList(start,end);
            productStorageOutRelateMapper.batchUpdateOutRelate(subList);
            System.out.println("============更新批次========="+(i+1));
        }
        System.out.println("=============更新完成===============");
        return null;
    }


    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateAutoProductStorageRelate() throws Exception{
        List<ProductStorageRelate> relates = productStorageRelateMapper.selectNotInStorageProduct();
        if(CollectionUtils.isEmpty(relates)){
            return;
        }
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String nowDutyDay = dutyMap.get("dutyDay");
        String nowWhiteDay = dutyMap.get("whiteDay");

        Iterator<ProductStorageRelate> iterator = relates.iterator();
        while (iterator.hasNext()){
            ProductStorageRelate next = iterator.next();
            if(StringUtils.equals(next.getWhiteDay(),nowWhiteDay)&&StringUtils.equals(next.getDutyDay(),nowDutyDay)){
                iterator.remove();
            }
        }
        if(CollectionUtils.isEmpty(relates)){
            return;
        }

        Map<String,List<ProductStorageRelate>> samBatchMap = Maps.newHashMap();
        for(ProductStorageRelate relate : relates ){
            String key = relate.getDutyDay() +"="+relate.getWhiteDay();
            if(samBatchMap.containsKey(key)){
                samBatchMap.get(key).add(relate);
            }else{
                List<ProductStorageRelate> r = Lists.newArrayList();
                r.add(relate);
                samBatchMap.put(key,r);
            }
        }
        for(String mapKey:samBatchMap.keySet()){
            Set<String> taskTypeSet = Sets.newHashSet();
            List<ProductStorageRelate> samRelates = samBatchMap.get(mapKey);
            for(ProductStorageRelate relate : samRelates ){
                taskTypeSet.add(relate.getTaskId());
            }
            String dutyDay = mapKey.split("=")[0];
            String whiteDay = mapKey.split("=")[1];
            QueryForm queryForm = new QueryForm();
            queryForm.setWhiteDay(whiteDay);
            queryForm.setDutyDay(dutyDay);
            String storageId = "";
            storageId = productStorageRelateMapper.selectStorageIdByWhiteDay(queryForm);
            if(StringUtils.isNotEmpty(storageId)){
                ProductStorage existStorage = productStorageService.getOnlyProductStorageById(storageId);
                if(null == existStorage){
                    throw new Exception("更新异常！");
                }
                existStorage.setStorageCount(existStorage.getStorageCount()+samRelates.size());
                existStorage.setStorageGradeCount(existStorage.getStorageGradeCount()+taskTypeSet.size());
                String resp = productStorageService.updateProductStorage(existStorage);
                if(StringUtils.isNotEmpty(resp)){
                    throw new Exception("更新异常！");
                }
            }else {
                storageId = CommonUtil.generateRandomNum("storage_");
                String yearMoth = generateUUID.getYearMoth();
                String key = yearMoth+"storage";
                int num = generateUUID.getNumberFlag(key);
                String code = "RK"+yearMoth+generateUUID.getThreeNumStr(num);
                ProductStorage productStorage = new ProductStorage();
                productStorage.setId(storageId);
                productStorage.setStorageCode(code);
                productStorage.setStorageType("1");
                productStorage.setStorageStatus("1");
                productStorage.setStorageCount(samRelates.size());
                productStorage.setStorageGradeCount(taskTypeSet.size());
                productStorage.setStorageUserName("admin");
                productStorage.setStorageUserId("");
                String resp = productStorageService.addProductStorage(productStorage);
                if(StringUtils.isNotEmpty(resp)){
                    throw new Exception("更新异常！");
                }
            }

            String resp = onDutyPersonService.updateOnDutyPersonLocked(dutyDay,whiteDay);
            if(StringUtils.isNotEmpty(resp)){
                throw new Exception(resp);
            }
            ProductStorageRelate update = new ProductStorageRelate();
            update.setStorageId(storageId);
            ProductStorageRelateExample example = new ProductStorageRelateExample();
            example.createCriteria().andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay);
            int count = productStorageRelateMapper.updateByExampleSelective(update,example);
            if(count < 1){
                throw new Exception("更新表异常！");
            }
        }

    }
}
